package com.cherrypt.api.core.util;

import com.cherrypt.api.model.dto.ImdbDto;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author intent
 * @date 2019/8/7 11:48
 * @about <link href='http://zzyitj.xyz/'/>
 */
public class ImdbUtils {
    private static final Logger logger = LoggerFactory.getLogger(ImdbUtils.class);

    private static final String IMDB_API_URL = "http://www.omdbapi.com";

    private static WebClient webClient = WebClient.builder()
            .baseUrl(IMDB_API_URL)
            .build();

    public static Mono<JsonNode> getImdbById(long imdbId) {
        return webClient.get()
                .uri("/?i=tt{imdbId}&apikey={key}", imdbId, CherryUtils.config.getImdbKey())
                .retrieve()
                .bodyToMono(JsonNode.class);
    }

    public static ImdbDto getImdb(JsonNode rootNode) {
        ImdbDto imdb = new ImdbDto();
        imdb.setImdbId(Long.valueOf(rootNode.get("imdbID").asText().replaceFirst("tt","")));
        imdb.setTitle(rootNode.get("Title").asText());
        imdb.setYear(rootNode.get("Year").asText());
        imdb.setRated(rootNode.get("Rated").asText());
        imdb.setReleased(rootNode.get("Released").asText());
        imdb.setRuntime(rootNode.get("Runtime").asText());
        imdb.setGenre(rootNode.get("Genre").asText());
        imdb.setDirector(rootNode.get("Director").asText());
        imdb.setWriter(rootNode.get("Writer").asText());
        imdb.setActors(rootNode.get("Actors").asText());
        imdb.setPlot(rootNode.get("Plot").asText());
        imdb.setLanguage(rootNode.get("Language").asText());
        imdb.setCountry(rootNode.get("Country").asText());
        imdb.setPoster(rootNode.get("Poster").asText());
        imdb.setImdbRating(Float.valueOf(rootNode.get("imdbRating").asText()));
        imdb.setImdbVotes(Integer.valueOf(rootNode.get("imdbVotes").asText().replaceAll(",", "")));
        imdb.setType(rootNode.get("Type").asText());
        imdb.setProduction(rootNode.get("Production").asText());
        return imdb;
    }
}
